<template>
  <!-- 选择采购产品 -->
  <a-modal :width="1000" v-model:visible="showChooseProductDialog" title="添加采购产品" title-align="start" :mask-closable="false" @cancel="closedDialog" :on-before-ok="chooseProduct">
    <a-space>
      <a-select style="width: 200px" :disabled="shopId ? true : false" v-model="shopIds" allow-clear placeholder="店铺" @change="getProductListByVal" :trigger-props="{ autoFitPopupMinWidth: true }">
        <a-option v-for="(shop, i) in shopList" :key="i" :value="shop.sellerMarketId" :label="shop.shopName" />
      </a-select>
      <a-input-group>
        <a-select style="width: 100px" v-model="valkey">
          <a-option value="skus" label="SKU" />
          <a-option value="asins" label="ASIN" />
          <a-option value="mskus" label="MSKU" />
          <a-option value="productName" label="产品名称" />
        </a-select>
        <a-input-search :style="{ width: '260px' }" v-model="keyword" placeholder="" @search="getProductListByVal" @press-enter="getProductListByVal" allow-clear>
          <template #suffix v-if="valkey != 'productName'">
            <a-popover position="br" trigger="click" v-model:popup-visible="showPopover" @click="mulValue = searchVal.keyword ? searchVal.keyword.replace(/,/g, '\n') : ''">
              <icon-more-vertical style="cursor: pointer; margin-left: 5px" />
              <template #content>
                <a-textarea placeholder="请输入，一行一个" v-model="mulValue" :style="{ width: '200px', height: '200px' }" />
                <div class="footer clearFix">
                  <div class="fl"> <a-button class="gray-outline" size="mini" @click="mulValue = ''">清空</a-button> </div>
                  <div class="fr">
                    <a-button size="mini" class="gray-outline" @click="showPopover = false">取消</a-button>
                    <a-button type="outline" size="mini" style="margin-left: 5px" @click="searchBatch">搜索</a-button>
                  </div>
                </div>
              </template>
            </a-popover>
          </template>
        </a-input-search>
      </a-input-group>
    </a-space>
    <p style="margin-bottom: 10px; text-align: right">已选中：{{ selectRow.length }}</p>
    <div class="table-model-wrap">
      <a-table size="mini" :data="productList" row-key="id" :loading="tableLoading" @selection-change="selectColumn" :row-selection="rowSelection" :scroll="{ y: 'calc(84vh - 260px)' }" :bordered="false" class="table-two-line table-model" :pagination="false">
        <template #columns>
          <a-table-column title="序号" :width="45">
            <template #cell="{ rowIndex }">
              <p>{{ rowIndex + 1 }}</p>
            </template>
          </a-table-column>
          <a-table-column data-index="shop" title="站点/店铺" :width="120">
            <template #cell="{ record }">
              <TextLimit :rows="1">{{ record.shopName }}</TextLimit>
            </template>
          </a-table-column>
          <a-table-column title="图片" :width="80">
            <template #cell="{ record }">
              <ImgPopover :src="getPicUrl(record)">
                <template #con>
                  <a-image width="40" height="40" fit="contain" :src="getPicUrl(record)" />
                </template>
              </ImgPopover>
            </template>
          </a-table-column>
          <a-table-column title="产品名称/SKU">
            <template #cell="{ record }">
              <TextLimit :rows="1">{{ record.productName || '--' }}</TextLimit>
              <TextLimit :rows="1">{{ record.sku || '--' }}</TextLimit>
            </template>
          </a-table-column>
          <a-table-column data-index="msku" title="MSKU/ASIN">
            <template #cell="{ record }">
              <TextLimit :rows="1">{{ record.msku || '--' }}</TextLimit>
              <TextLimit :rows="1">{{ record.asin || '--' }}</TextLimit>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </div>
    <div class="pagination-footer">
      <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import ImgPopover from '@/components/imgPopover.vue'
  import { findReplenishPage } from '@/api/purchase'
  import { Message } from '@arco-design/web-vue'
  import useBaseDataStore from '@/store/modules/base-data'

  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: '添加采购产品',
    },
    shopId: {
      type: String,
    },
  })
  onMounted(async () => {
    getShopList()
    getProductList()
  })

  const showChooseProductDialog = ref(props.isShow)
  const shopIds = ref(props.shopId)
  const valkey = ref('skus')
  const keyword = ref()
  const searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
  })
  const rowSelection = ref({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  const selectRow = ref([])
  const total = ref(0)
  const showPopover = ref(false)
  const mulValue = ref()
  const productList = ref([])
  const shopList = ref<Array<any>>([])
  const productListMap = ref({})
  const tableLoading = ref(false)
  const useBaseData = useBaseDataStore()

  function selectColumn(val: any) {
    selectRow.value = val
  }
  // 获取店铺
  async function getShopList() {
    await useBaseData.getShopListAndShare()
    shopList.value = useBaseData.shopListAndShare || []
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getProductList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getProductList()
  }
  function searchBatch() {
    keyword.value = mulValue.value?.split('\n')?.join(',')
    getProductListByVal()
    showPopover.value = false
  }
  function getProductListByVal() {
    searchVal.value.pageNum = 1
    getProductList()
  }
  //产品列表数据
  async function getProductList() {
    let parmas = JSON.parse(JSON.stringify(searchVal.value))
    parmas[valkey.value] = keyword.value
    parmas.shopIds = shopIds.value
    tableLoading.value = true
    const res: any = await findReplenishPage(parmas)
    tableLoading.value = false
    productList.value = res?.data?.records || []
    total.value = res?.data?.total || 0
    productListMap.value = {}
    productList.value.forEach((el: any) => {
      productListMap.value[el.id] = el
    })
  }
  // 显示图片
  function getPicUrl(item: any) {
    return item?.productImgs?.[0]
  }
  // 选择产品
  function chooseProduct() {
    if (!selectRow.value.length) {
      Message.error('请选择产品')
      return false
    }
    let list = selectRow.value.map((id: string) => productListMap.value[id])
    emit('success', list)
    emit('closed')
  }
  // 关闭
  function closedDialog() {
    showChooseProductDialog.value = false
    emit('closed')
  }
</script>
<style lang="less" scoped>
  .info-text {
    color: #999;
    margin-top: 10px;
  }
  .pagination-footer {
    margin-top: 10px;
  }
</style>
